#!/bin/bash

# 加载配置
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "${SCRIPT_DIR}/config.sh"

# 检查权限和环境
check_root
check_install_env

# 从services.json获取服务列表（反向顺序）
SERVICES=$(jq -r '.start_order[]' services.json | tac)

# 停止所有微服务
info "开始停止微服务..."
total=$(echo "$SERVICES" | wc -w)
current=1

for service in $SERVICES; do
    info "[$current/$total] 停止微服务: ${service}"
    if pgrep -f "${service}\$" > /dev/null; then
        cmd=$(ps -p $(pgrep -f "${service}\$") -o cmd=)
        info "[$current/$total] 正在停止: $cmd"
        pkill -f "${service}\$"
        sleep 1
        if ! pgrep -f "${service}\$" > /dev/null; then
            info "[$current/$total] ${service} 已停止"
        else
            warn "[$current/$total] ${service} 停止超时，尝试强制终止"
            pkill -9 -f "${service}\$"
            sleep 1
            if ! pgrep -f "${service}\$" > /dev/null; then
                info "[$current/$total] ${service} 已强制停止"
            else
                error "[$current/$total] ${service} 无法停止"
            fi
        fi
    else
        info "[$current/$total] ${service} 未在运行"
    fi
    current=$((current + 1))
done

info "所有微服务已停止" 